package com.tabnet.servlet.client;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tabnet.beans.personnes.Client;
import com.tabnet.beans.produit.Produit;
import com.tabnet.dao.DAOAccessoire;
import com.tabnet.dao.DAOCommande;
import com.tabnet.dao.DAOException;
import com.tabnet.dao.DAOFactory;
import com.tabnet.dao.DAOLigneCommande;
import com.tabnet.form.client.AjoutPanierForm;

public class AjoutPanier extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
    public static final String ATT_FORM        		= "form";
    public static final String ATT_COMMANDE         = "commande";
    public static final String SESSION_USER 		= "sessionClient";
    public static final String SESSION_PRODUIT		= "produit";
    public static final String VUE_SUCCES      		= "/adminClient/accueil.jsp";
    public static final String VUE        			= "/index.jsp";
    
    private DAOCommande _DAOCommande;
    private DAOAccessoire _DAOAccessoire;
    private DAOLigneCommande _DAOLigneCommande;
    
    public void init() throws ServletException {
        /* Récupération d'une instance de notre DAO Utilisateur */
    	try {
			this._DAOCommande = DAOFactory.getInstance().getCommandeDAO();
			this._DAOAccessoire = DAOFactory.getInstance().getAccessoireDAO();
			this._DAOLigneCommande = DAOFactory.getInstance().getLigneCommandeDAO();
		}
    	catch (DAOException e) {
			e.printStackTrace();
		}
    }
    
    public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
    	this.doPost(request, response);
    }

    public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
    	/* Récupération du client dans la session */
        HttpSession session = request.getSession();
        
    	Client oClient = (Client) session.getAttribute(SESSION_USER);
    	Produit oProduit = (Produit) session.getAttribute(SESSION_PRODUIT);
    	
    	if(oClient == null)
            this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );
    	
        AjoutPanierForm form = new AjoutPanierForm(this._DAOCommande, this._DAOAccessoire, this._DAOLigneCommande);
    	form.ajoutPanier(request, oClient, oProduit);
    	
        if ( form.getErreurs().isEmpty() ) {
        	session.setAttribute( SESSION_USER, oClient );
            response.sendRedirect( request.getContextPath() + VUE_SUCCES );
        }
        else
            this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );
    }
    
}
